package com.briup.estore.util;

import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;

import java.io.IOException;
import java.io.InputStream;

/**
 * 简单封装Mybatis的sqlSession对象
 */
public class MybatisSqlSessionFactory {
    private static SqlSessionFactory sqlSessionFactory;

    public static SqlSessionFactory getSqlSessionFactory() {
        if(sqlSessionFactory == null){
            InputStream is = null;
            try {
                is = Resources.getResourceAsStream("mybatis-config.xml");
                sqlSessionFactory = new SqlSessionFactoryBuilder().build(is);
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return sqlSessionFactory;
    }
    // 一个environment就是一个sqlSessionFactory

    public static SqlSession openSession(){
        return openSession(true);
    }
    public static SqlSession openSession(boolean autocommit){
        return getSqlSessionFactory().openSession(autocommit);
    }
}
